import json
import random

from django.contrib.auth import authenticate, login


# import redis
from django.http import HttpResponse, JsonResponse

from celery_tasks.sms.tasks import send_sms_code


import re
from django import http

# Create your views here.


# 图形验证码
from django.views import View
from django_redis import get_redis_connection
from redis import Redis

from libs.captcha.captcha import captcha
from utils.smsutils import SmsUtil


class ImageCodeView(View):
    def get(self, requset, uuid):
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        print(text)
        redis_conn.setex('img_%s' % uuid, 300, text)

        return HttpResponse(image, content_type='image/jpeg')


# 短信验证码
class SmsView(View):

    def get(self, request, mobile):
        # 校验手机格式是否正确
        if not mobile:
            return JsonResponse({'code': 300, 'errmsg': '手机号为空'})

        # 正则验证

        # 校验图片验证码是否正确
        # 用户发过来的图片验证码image_code
        image_code = request.GET.get('image_code')
        image_code_uuid = request.GET.get('image_code_id')

        try:
            # 获取保存都在redis里的图片验证码
            redis_conn:Redis = get_redis_connection('code')
            print(redis_conn)
            print('image_code_uuid', image_code_uuid)
            image_code_redis = redis_conn.get('img_%s' % image_code_uuid)
            print('image_code_redis', image_code_redis)

            if not image_code_redis:
                print(1)
                return JsonResponse({'code': 400, 'errmsg': '验证码过期'})
            image_code_redis = image_code_redis.decode()

            if image_code.lower() != image_code_redis.lower():
                print(2)
                return JsonResponse({'code': 500, 'errmsg': '图片验证码错了'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 600, 'errmsg': '网络异常'})

        # 给这个手机号发送短信　第三方
        # 简单方式

        print('发送短信给', mobile)
        flag_send = redis_conn.get('flag_%s' % mobile)
        # 生成短信验证码　　　　如果不够六位左侧补０
        if flag_send:
            return JsonResponse({'code': 110, 'errmsg': '短信已经发送，请耐心等待'})
        sms_code = '%06d' % random.randint(0, 999999)
        print('你的短信验证码为', sms_code)

        # 调用单例方式
        #SmsUtil().send_message(mobile=mobile, code=sms_code)

        send_sms_code.delay(mobile=mobile, sms_code=sms_code)

        pl = redis_conn.pipeline()
        pl.setex('smscode_%s' % mobile, 60, sms_code)
        pl.setex('flag_%s' % mobile, 60, 1)
        pl.execute()
        # 保存的key smscode_手机号
        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})



